<template>
  <div class="vote-detail">
    <el-card>
      <template #header>
        <div class="vote-header">
          <h2>{{ vote.title }}</h2>
          <div class="vote-status">
            <el-tag :type="getStatusType">{{ getStatusText }}</el-tag>
          </div>
        </div>
      </template>

      <div class="vote-info">
        <p class="description">{{ vote.description }}</p>
        <div class="time-info">
          <p>开始时间：{{ formatDate(vote.startTime) }}</p>
          <p>结束时间：{{ formatDate(vote.endTime) }}</p>
        </div>
      </div>

      <div class="vote-options" v-if="!isVoteEnded">
        <h3>请选择您的选项：</h3>
        <el-radio-group v-model="selectedOption">
          <div v-for="option in vote.options" :key="option.id" class="option-item">
            <el-radio :label="option.id">{{ option.content }}</el-radio>
          </div>
        </el-radio-group>
        <el-button 
          type="primary" 
          @click="submitVote" 
          :loading="submitting"
          :disabled="!selectedOption || hasVotedToday"
          class="submit-button"
        >
          {{ hasVotedToday ? '今日已投票' : '提交投票' }}
        </el-button>
      </div>

      <div class="vote-results" v-else>
        <h3>投票结果：</h3>
        <div v-for="option in vote.options" :key="option.id" class="result-item">
          <div class="result-header">
            <span>{{ option.content }}</span>
            <span>{{ option.voteCount }} 票</span>
          </div>
          <el-progress 
            :percentage="calculatePercentage(option.voteCount)" 
            :format="format"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

export default {
  name: 'VoteDetail',
  setup() {
    const route = useRoute()
    const store = useStore()
    const vote = ref({})
    const selectedOption = ref(null)
    const submitting = ref(false)
    const hasVotedToday = ref(false)

    const fetchVoteDetail = async () => {
      try {
        const response = await store.dispatch('fetchVoteDetail', route.params.id)
        vote.value = response.data
        checkVoteStatus()
      } catch (error) {
        ElMessage.error('获取投票详情失败')
      }
    }

    const checkVoteStatus = async () => {
      try {
        const response = await store.dispatch('checkVoteStatus', route.params.id)
        hasVotedToday.value = response.data.hasVoted
      } catch (error) {
        console.error('检查投票状态失败:', error)
      }
    }

    const submitVote = async () => {
      if (!selectedOption.value) {
        ElMessage.warning('请选择一个选项')
        return
      }

      try {
        submitting.value = true
        await store.dispatch('castVote', {
          topicId: vote.value.id,
          optionId: selectedOption.value
        })
        ElMessage.success('投票成功')
        await fetchVoteDetail()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '投票失败')
      } finally {
        submitting.value = false
      }
    }

    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }

    const calculatePercentage = (count) => {
      const total = vote.value.options.reduce((sum, option) => sum + option.voteCount, 0)
      return total === 0 ? 0 : Math.round((count / total) * 100)
    }

    const format = (percentage) => {
      return percentage + '%'
    }

    const isVoteEnded = computed(() => {
      return dayjs(vote.value.endTime).isBefore(dayjs())
    })

    const getStatusType = computed(() => {
      const now = dayjs()
      if (dayjs(vote.value.startTime).isAfter(now)) return 'info'
      if (dayjs(vote.value.endTime).isBefore(now)) return 'danger'
      return 'success'
    })

    const getStatusText = computed(() => {
      const now = dayjs()
      if (dayjs(vote.value.startTime).isAfter(now)) return '即将开始'
      if (dayjs(vote.value.endTime).isBefore(now)) return '已结束'
      return '进行中'
    })

    onMounted(() => {
      fetchVoteDetail()
    })

    return {
      vote,
      selectedOption,
      submitting,
      hasVotedToday,
      isVoteEnded,
      getStatusType,
      getStatusText,
      formatDate,
      submitVote,
      calculatePercentage,
      format
    }
  }
}
</script>

<style scoped>
.vote-detail {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.vote-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.vote-header h2 {
  margin: 0;
}

.description {
  font-size: 16px;
  color: #666;
  margin: 20px 0;
}

.time-info {
  color: #666;
  margin-bottom: 20px;
}

.time-info p {
  margin: 5px 0;
}

.option-item {
  margin: 15px 0;
}

.submit-button {
  margin-top: 20px;
  width: 100%;
}

.result-item {
  margin: 20px 0;
}

.result-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.el-progress {
  margin-top: 5px;
}
</style>
